package com.hsnn.medstgmini.pro.project.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.crypto.CryptoUtil;
import com.hsnn.medstgmini.crypto.KeyStoreUtil;
import com.hsnn.medstgmini.crypto.impl.CryptoManagerImpl;
import com.hsnn.medstgmini.exception.MSException;
import com.hsnn.medstgmini.pro.project.model.BidProject;
import com.hsnn.medstgmini.pro.project.model.form.BidProjectForm;
import com.hsnn.medstgmini.pro.project.model.form.ProdProjectForm;
import com.hsnn.medstgmini.pro.project.service.BidProjectManager;
import com.hsnn.medstgmini.pro.project.service.ProdProjectManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;

/**
 * @category 生产企业项目管理
 * @author 蔡春龙
 * @date 2015年8月24日
 */
@Controller
@RequestMapping("/prodProject")
public class ProdProjectController {

	private static final Logger logger = LoggerFactory
			.getLogger(ProdProjectController.class);

	@Autowired
	private ProdProjectManager prodProjectManager;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private HttpSession session;
	
	@Autowired
	private BidProjectManager bidProjectManager;
	/**
	 * @category 获取当前登陆人信息
	 * @author 言科
	 * @date 2015年7月22日 SysUser
	 */
	public SysUser getUser() {
		return (SysUser) session.getAttribute(Constants.USERINFO);
	}

	/**
	 * @category 招标项目查看页面
	 * @date 2015年8月24日
	 * @return
	 */
	@RequestMapping("/toProjectList")
	public String toProjectList(Model model) {
		model.addAttribute("date", DateUtil.date());
		return "/pro/project/prod/projectList";
	}

	/**
	 * @category 招标项目查看页面查询
	 * @date 2015年8月24日
	 * @return
	 */
	@RequestMapping("/getProjectList")
	@ResponseBody
	public Pagination getProjectList(ProdProjectForm form) {
		Pagination page = new Pagination(request);
		SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
		try {
			String defalutProjId=  user.getDefaultProjId();
			if (StringUtils.isNotBlank(defalutProjId)) {
				page.getConditions().put("defalutProjId", defalutProjId);
				form.setProjId(defalutProjId);
			}
			page.setForm(form);
			prodProjectManager.getProjectList(page, getUser());
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 招标时间段查看页面
	 * @date 2015年8月24日
	 * @return
	 */
	@RequestMapping("/toProjectListTimeSee")
	public String toProjectListTimeSee(RedirectAttributes attr) {
		logger.info("enter toProjectList method!");
		SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
		String defalutProjId=  user.getDefaultProjId();
		if ( StringUtils.isNotBlank(defalutProjId) ) {
			 attr.addAttribute("projId",defalutProjId);  
			 
		     return "redirect:/prodProject/toProjectTimeView.html";
		}
		return "/pro/project/prod/projectListTimeSee";
	}

	/**
	 * @category 招标时间段查看页面查询
	 * @date 2015年8月24日
	 * @return
	 */
	@RequestMapping("/getProjectListTimeSee")
	@ResponseBody
	public Pagination getProjectListTimeSee(ProdProjectForm form) {
		Pagination page = new Pagination(request);
		try {
			page.setForm(form);
			prodProjectManager.getProjectListTimeSee(page, getUser());
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 报价密码管理页面
	 * @date 2015年8月24日
	 * @return
	 */
	@RequestMapping("/toProjectListPassword")
	public String toProjectListPassword(RedirectAttributes attr) {
		logger.info("enter toProjectList method!");
		SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
		String defalutProjId=  user.getDefaultProjId();
		if ( StringUtils.isNotBlank(defalutProjId) ) {
			BidProject bp = bidProjectManager.getBidProjectById(defalutProjId);
			 attr.addAttribute("name",bp.getName());  
			 attr.addAttribute("projId",defalutProjId);  
		     return "redirect:/prodProject/toPasswordSetDefault.html";
		}
		return "/pro/project/prod/projectListPassword";
	}
	
	/**
	 * @category 报价密码管理页面（默认）
	 * @date 2015年9月16日14:24:37
	 * @author  应晓川
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toPasswordSetDefault")
	public String toPasswordSetDefault() throws UnsupportedEncodingException {
		logger.info("enter toPasswordSetDefault method!");
		String name = new String(request.getParameter("name").getBytes("iso8859-1"),"utf-8");
		request.setAttribute("name", name);
		request.setAttribute("projId", request.getParameter("projId"));
		return "/pro/project/prod/passwordSetDefault";
	}

	/**
	 * @category 报价密码管理页面查询
	 * @date 2015年8月24日
	 * @return
	 */
	@RequestMapping("/getProjectListPassword")
	@ResponseBody
	public Pagination getProjectListPassword(ProdProjectForm form) {
		Pagination page = new Pagination(request);
		try {
			page.setForm(form);
			prodProjectManager.getProjectListPassword(page, getUser());
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 分页查询已报名的有效项目
	 * @date 2015年8月26日
	 * @param form
	 * @return
	 */
	@RequestMapping("/getMyProjectList")
	@ResponseBody
	public Pagination getMyProjectList(ProdProjectForm form) {
		Pagination page = new Pagination(request);
		try {
			page.setForm(form);
			prodProjectManager.getMyProjectList(page, getUser());
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 企业投标报名
	 * @date 2015年8月24日
	 * @return
	 */
	@RequestMapping("/enroll")
	@ResponseBody
	public Pagination enroll(String projId) {
		Pagination page = new Pagination(request);
		try {
			if (StringUtils.isNotBlank(projId)) {
				prodProjectManager.enroll(projId, getUser());
				page.setSuccess(true);
			}
		} catch (MSException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			page.setSuccess(false);
			page.setMsg(e.getMsg());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 生产企业跳转项目时间段查看页面
	 * @date 2015年8月24日
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/toProjectTimeView")
	public String toProjectTimeView(Model model, String projId) throws IOException {
		logger.info("enter toProjectTimeView method!");
		SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
		String defalutProjId=  user.getDefaultProjId();
		if(StringUtils.isNotBlank(defalutProjId)){
			request.setAttribute("defalutProjId", defalutProjId);
		}
		Map<String, Object> map = bidProjectManager.getDataDetail(projId);
		request.setAttribute("name", map.get("name"));
		ProdProjectForm form = prodProjectManager.getProjectTimeView(projId);
		model.addAttribute("form", form);
		model.addAttribute("date", ParseDate.parseFullFormat(new Date()));
		List<BidProjectForm> info = bidProjectManager.getSettimeDataDetail(projId);
		request.setAttribute("projStart", info.get(0));
		request.setAttribute("projEnd", info.get(info.size()-1));
		info.remove(info.size()-1);
		info.remove(0);
		request.setAttribute("info", info);
//		String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
//		if(StringUtils.isNotBlank(name)){
//			request.setAttribute("name", name);			
//		}
		return "/pro/project/prod/projectTimeView";
	}

	/**
	 * @category 生产企业跳转项目报价解密密码设置页面
	 * @date 2015年8月24日
	 * @param model
	 * @param projId
	 * @return
	 */
	@RequestMapping("/toPasswordSet")
	public String toPasswordSet(Model model, String projId) {
		StdCompinfo compInfo = getUser().getInfo();
		String compId = "";
		if (compInfo != null) {
			compId = compInfo.getCompId();
		}
		String defaultP = request.getParameter("defaultP");
		if(StringUtils.isNotBlank(defaultP)){
			model.addAttribute("defaultP", defaultP);
		}
		String password = prodProjectManager.getPassword(projId, compId);
		model.addAttribute("projId", projId);
		model.addAttribute("compId", compId);
		model.addAttribute("hasPassword", StringUtils.isNotBlank(password));
		return "/pro/project/prod/passwordSet";
	}

	/**
	 * @category 设置密码
	 * @date 2015年8月24日
	 * @param form
	 * @return
	 */
	@RequestMapping("/setPassword")
	@ResponseBody
	public Pagination setPassword(ProdProjectForm form) {
		Pagination page = new Pagination(request);
		try {

			// 获取密钥
			SecretKey sk = KeyStoreUtil.getSecretKey(
					session.getServletContext().getRealPath(
							"/WEB-INF/keystore/sysKeyStore"), "330000",
					"secretKeyAlias");

			// 获取企业id
			StdCompinfo compInfo = getUser().getInfo();
			String compId = "";
			if (compInfo != null) {
				compId = compInfo.getCompId();
			}

			// 如果有原密码，校验原密码是否正确
			String oldPassword = prodProjectManager.getPassword(
					form.getProjId(), compId);
			if (StringUtils.isNotBlank(oldPassword)) {
				byte[] bt = CryptoUtil.decode(oldPassword);
				oldPassword = CryptoManagerImpl.decrypt(sk, bt);
				if (!oldPassword.equals(form.getOldPassword())) {
					page.setSuccess(false);
					page.setMsg("原密码不正确！");
					return page;
				}
			}

			// 加密并保存新密码
			String password = form.getPassword();
			if (StringUtils.isBlank(password)) {
				page.setSuccess(false);
				page.setMsg("请输入密码！");
			} else {
				byte[] bt = CryptoManagerImpl.encrypt(sk, password);
				password = CryptoUtil.encode(bt);
				form.setPassword(password);
				prodProjectManager.setPassword(form, getUser());
				page.setSuccess(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			page.setSuccess(false);
		}
		return page;
	}

}
